import { Component, OnInit } from '@angular/core';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { ApiService } from '@core/services/http/api.service';
import { BiService } from '../../../bi.service';

@Component({
  selector: 'loss-assessment',
  templateUrl: './loss-assessment.component.html',
  styleUrls: ['./loss-assessment.component.scss'],
})
export class LossAssessmentComponent implements OnInit {

  // 定损报案分析

  // 车险转定损
  carInsuranceField: FormlyFieldConfig[] = [
    {
      key: 'INSURANCE_COMPANY_ID',
      type: 'select',
      templateOptions: {
        label: '保险公司',
        api: 'crm.insuranceCompany.findAll',
        searchFormId: 'cm.dept.findAllServicePlan',
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        downFormatter: '"["+ value.id + "]" + value.name',
        valueFormatter: '"["+ value.id + "]" + value.name',
        addSame: 'false',
        uniqueKey: 'id',
        multiple: 'true',
        divCol: 5,
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'month',
        },
        divCol: 5,
      },
    },
  ];
  carInsuranceModel: any = {};

  // 柱形图
  carInsuranceBarOption: any = {
    tooltip: {
      trigger: 'item',
      // axisPointer: {
      //   type: 'cross',
      //   crossStyle: {
      //     color: '#999',
      //   },
      // },
      formatter: this.showCarInsuranceBarTooltip,
    },
    legend: {
      data: ['案件数', '转定损'],
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        show: true,
        interval: 0,
        width: 100,
        overflow: 'break',
      },
    },
    yAxis: [
      {
        name: '单数',
        type: 'value',
        axisLabel: {
          formatter: '{value}',
        },
      },
    ],
    series: [
      { name: '案件数', type: 'bar', stack: '总数', emphasis: { focus: 'series' } },
      { name: '转定损', type: 'bar', stack: '总数', emphasis: { focus: 'series' } },
    ],
  };
  carInsuranceBarData: any;
  carInsuranceBarLoading: boolean = false;

  // 表格
  carInsuranceFormData: any;
  carInsuranceFormLoading: boolean = false;

  // 商务审计效率
  reviewOption: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['单量', '平均耗时'],
    },
    xAxis: {
      type: 'category',
    },
    yAxis: [
      {
        name: '单量',
        type: 'value',
        axisLabel: {
          formatter: '{value} 单',
        },
      },
      {
        name: '耗时',
        type: 'value',
        axisLabel: {
          formatter: '{value} 分钟',
        },
      },
    ],
    series: [
      { name: '单量', type: 'bar', label: { show: true } },
      // { name: '超时', type: 'bar', label: { show: true } },
      { name: '平均耗时', type: 'line', yAxisIndex: 1 },
    ],
  };
  reviewField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  reviewData: any;
  reviewModel: any = {};
  reviewLoading: boolean = false;

  // 保险公司定损
  insuranceCompanyField: FormlyFieldConfig[] = [
    {
      key: 'INSURANCE_COMPANY_ID',
      type: 'select',
      templateOptions: {
        label: '保险公司',
        api: 'crm.insuranceCompany.findAll',
        searchFormId: 'crm.insuranceCompany.findAll',
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        downFormatter: '"["+ value.id + "]" + value.name',
        valueFormatter: '"["+ value.id + "]" + value.name',
        addSame: 'false',
        uniqueKey: 'id',
        multiple: 'true',
        divCol: 5,
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'month',
        },
        divCol: 5,
      },
    },
  ];
  insuranceCompanyModel: any = {};

  // 饼图
  insuranceCompanyPieOption: any = {
    tooltip: {
      trigger: 'item',
      formatter: this.showTooltip,
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll',
    },
    series: [
      {
        name: '占比', type: 'pie', center: ['60%', '50%'], radius: '50%', emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  insuranceCompanyPieData: any;
  insuranceCompanyPieLoading: boolean = false;

  // 柱形图
  insuranceCompanyBarOption: any = {
    tooltip: {
      trigger: 'item',
      formatter: this.showInsuranceCompanyBarTooltip,
    },
    legend: {
      data: ['成本金额', '定损已收款金额'],
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        show: true,
        interval: 0,
        width: 100,
        overflow: 'break',
      },
    },
    yAxis: [
      {
        name: '金额',
        type: 'value',
        axisLabel: {
          formatter: '{value}',
        },
      },
    ],
    series: [
      { name: '成本金额', type: 'bar', stack: '总数', emphasis: { focus: 'series' } },
      { name: '定损已收款金额', type: 'bar', stack: '总数', emphasis: { focus: 'series' } },
    ],
  };
  insuranceCompanyBarData: any;
  insuranceCompanyBarLoading: boolean = false;

  // 表格
  insuranceCompanyFormData: any;
  insuranceCompanyFormLoading: boolean = false;


  constructor(
    private apiService: ApiService,
    private bi: BiService,
  ) {

  }

  ngOnInit() {
    setTimeout(() => {

      this.refreshCarInsuranceData();
      this.refreshReviewData();
      this.refreshInsuranceCompanyData();
    }, 1000);
  }

  refreshCarInsuranceData() {
    let date = this.bi.conversionMonth(this.carInsuranceModel['DATE']);
    let nowDate = this.bi.currentMonthsList(date);
    let id = this.carInsuranceModel['INSURANCE_COMPANY_ID'] ? this.carInsuranceModel['INSURANCE_COMPANY_ID'] : [];

    const data = {
      INSURANCE_COMPANY_ID: id,
      DATE_START: nowDate[0],
      DATE_END: nowDate[1],
    };

    let barApi = 'businessControl.insuranceReportBarChart';

    this.carInsuranceBarLoading = true;
    this.apiService.post(barApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('车险转定损-柱形图', body);
      // let dimensions = [];
      let source = [['APP_CODE', 'TOTAL', 'SETTLEMENT']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(name);
          source.push([
            res['APP_CODE'],
            res['TOTAL'] ? res['TOTAL'] : 0,
            res['SETTLEMENT'] ? res['SETTLEMENT'] : 0,
            res['REPEAL'] ? res['REPEAL'] : 0,
            res['STORE'] ? res['STORE'] : 0,
            res['BACKSTAGE'] ? res['BACKSTAGE'] : 0,
            res['YearOnYear'] ? res['YearOnYear'] : 0,
            res['ChainRatio'] ? res['ChainRatio'] : 0,
          ]);
        });
      }
      this.carInsuranceBarData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };

      this.carInsuranceBarLoading = false;
    });

    let formApi = 'businessControl.insuranceReportFrom';

    this.carInsuranceFormLoading = true;
    this.carInsuranceFormData = [];
    this.apiService.post(formApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('车险转定损-表格', body);
      if (body && body.length != 0) {
        this.carInsuranceFormData = body;
      }
      this.carInsuranceFormLoading = false;
    });
  }

  showCarInsuranceBarTooltip(params) {
    let tooltip =
      '<div class="apes-charts-tooltip-p">' + '保险公司 : ' + '<span class="apes-charts-tooltip-text">' + params.data[0] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '案件数 : ' + '<span class="apes-charts-tooltip-text">' + params.data[1] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '终止数 : ' + '<span class="apes-charts-tooltip-text">' + params.data[3] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '门店跟进 : ' + '<span class="apes-charts-tooltip-text">' + params.data[4] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '后台跟进 : ' + '<span class="apes-charts-tooltip-text">' + params.data[5] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '转定损 : ' + '<span class="apes-charts-tooltip-text">' + params.data[2] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '同比 : ' + '<span class="apes-charts-tooltip-text">' + params.data[6] + '%</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '环比 : ' + '<span class="apes-charts-tooltip-text">' + params.data[7] + '%</span></div>';
    return tooltip;
  }

  refreshReviewData() {
    let date = this.bi.conversionMonths(this.reviewModel['DATE'], 6);

    const data = {
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let api = 'businessControl.queryBusinessApproveData';

    this.reviewLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('商务审计效率', body);
      // let dimensions = [];
      let source = [['STATISTIC_DATE','ORDER_NUMBER','claimRate']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(name);
          source.push([
            res['STATISTIC_DATE'],
            res['ORDER_NUMBER'],
            res['claimRate'],
          ]);
        });
      }
      this.reviewData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };
      this.reviewLoading = false;
    });
  }

  refreshInsuranceCompanyData() {
    let date = this.bi.conversionMonth(this.insuranceCompanyModel['DATE']);
    let nowDate = this.bi.currentMonthsList(date);
    let id = this.insuranceCompanyModel['INSURANCE_COMPANY_ID'] ? this.insuranceCompanyModel['INSURANCE_COMPANY_ID'] : [];

    const data = {
      INSURANCE_COMPANY_ID: id,
      DATE_START: nowDate[0],
      DATE_END: nowDate[1],
    };

    let pieApi = 'businessControl.settlementClaimPieChart';

    this.insuranceCompanyPieLoading = true;
    this.apiService.post(pieApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('保险公司定损-饼图', body);
      let dimensions = [];
      let source = [];
      if (body && body.length != 0) {
        body.forEach((res) => {
          dimensions.push(res['CLASS_NAME']);
          source.push([
            res['CLASS_NAME'],
            res['AMOUNT'],
          ]);
        });
      }
      this.insuranceCompanyPieData = {
        dataset: {
          dimensions: dimensions,
          source: source,
        },
      };
      this.insuranceCompanyPieLoading = false;
    });

    let barApi = 'businessControl.settlementClaimBarChart';

    this.insuranceCompanyBarLoading = true;
    this.apiService.post(barApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('保险公司定损-柱形图', body);
      // let dimensions = [];
      let source = [['NAME', 'PRICE_COST_UNIT_IN_TAX', 'FIXED_LOSS_AMOUNT']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(res['INSURANCE_COMPANY']);
          source.push([
            res['NAME'],
            res['PRICE_COST_UNIT_IN_TAX'],
            res['FIXED_LOSS_AMOUNT'],
            res['STATISTIC_DATE'],
            res['YearOnYear'],
            res['ChainRatio'],
          ]);
        });
      }
      this.insuranceCompanyBarData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };
      this.insuranceCompanyBarLoading = false;
    });

    let formApi = 'businessControl.settlementClaimFrom';

    this.insuranceCompanyFormLoading = true;
    this.insuranceCompanyFormData = [];
    this.apiService.post(formApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('保险公司定损-表格', body);
      if (body && body.length != 0) {
        this.insuranceCompanyFormData = body;
      }
      this.insuranceCompanyFormLoading = false;
    });
  }

  showTooltip(params) {
    let tooltip = params.seriesName + '<br/>' + params.name + ':' + params.data[1] + '(' + params.percent + '%)';
    return tooltip;
  }

  showInsuranceCompanyBarTooltip(params) {
    let tooltip =
      '<div class="apes-charts-tooltip-p"><span class="apes-charts-tooltip-text">' + params.data[3] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '保险公司 : ' + '<span class="apes-charts-tooltip-text">' + params.data[0] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '定损收款总金额 : ' + '<span class="apes-charts-tooltip-text">' + params.data[2] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '成本金额 : ' + '<span class="apes-charts-tooltip-text">' + params.data[1] + '</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '同比 : ' + '<span class="apes-charts-tooltip-text">' + params.data[4] + '%</span></div>' +
      '<div class="apes-charts-tooltip-p">' + '环比 : ' + '<span class="apes-charts-tooltip-text">' + params.data[5] + '%</span></div>';
    return tooltip;
  }
}

